<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form class="antd-modal-form" v-bind="formItemLayout" ref="formRef" name="ContractDetailInfoForm">
          <a-row>
						<a-col :span="24">
							<a-form-item label="单位名称" v-bind="validateInfos.itemName" id="ContractDetailInfo-itemName" name="itemName">
								<a-input v-model:value="formData.itemName" placeholder="请输入单位名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<!-- 隐藏合同编号字段 -->
						<!-- <a-col :span="24">
							<a-form-item label="合同编号" v-bind="validateInfos.contractNumber" id="ContractDetailInfo-contractNumber" name="contractNumber">
								<a-input v-model:value="formData.contractNumber" placeholder="请输入合同编号"  allow-clear ></a-input>
							</a-form-item>
						</a-col> -->
						<a-col :span="24">
							<a-form-item label="单位" v-bind="validateInfos.unit" id="ContractDetailInfo-unit" name="unit">
								<a-select v-model:value="formData.unit" placeholder="请选择单位" allow-clear>
									<a-select-option value="年">年</a-select-option>
									<a-select-option value="次">次</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="产品类型" v-bind="validateInfos.productType" id="ContractDetailInfo-productType" name="productType">
								<a-select
									v-model:value="formData.productType"
									placeholder="请选择产品类型"
									allow-clear
									@change="handleProductTypeChange"
									:loading="productTypeLoading"
								>
									<a-select-option
										v-for="item in productTypeOptions"
										:key="item.id"
										:value="item.productTypeName || item.productType || item.name"
									>
										{{ item.productTypeName || item.productType || item.name }}
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="产品内容" v-bind="validateInfos.productContent" id="ContractDetailInfo-productContent" name="productContent">
								<a-select
									v-model:value="formData.productContent"
									placeholder="请选择产品内容"
									allow-clear
									:disabled="!formData.productType"
									:loading="productContentLoading"
								>
									<a-select-option
										v-for="item in productContentOptions"
										:key="item.id"
										:value="item.productName || item.name"
									>
										{{ item.productName || item.name }}
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="数量" v-bind="validateInfos.allCount" id="ContractDetailInfo-allCount" name="allCount">
								<a-input-number v-model:value="formData.allCount" placeholder="请输入数量" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="合同金额" v-bind="validateInfos.amount" id="ContractDetailInfo-amount" name="amount">
								<a-input-number v-model:value="formData.amount" placeholder="请输入合同金额" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="到账总额" v-bind="validateInfos.arriveAmount" id="ContractDetailInfo-arriveAmount" name="arriveAmount">
								<a-input-number v-model:value="formData.arriveAmount" placeholder="请输入到账总额" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="第三方支出" v-bind="validateInfos.thirdExpense" id="ContractDetailInfo-thirdExpense" name="thirdExpense">
								<a-input-number v-model:value="formData.thirdExpense" placeholder="请输入第三方支出" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="合同净额" v-bind="validateInfos.netAmount" id="ContractDetailInfo-netAmount" name="netAmount">
								<a-input-number v-model:value="formData.netAmount" placeholder="请输入合同净额" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="含税单价" v-bind="validateInfos.taxPrice" id="ContractDetailInfo-taxPrice" name="taxPrice">
								<a-input-number v-model:value="formData.taxPrice" placeholder="请输入含税单价" style="width: 100%" />
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, onMounted, inject, defineProps, unref, watch } from 'vue';
  import { defHttp } from '/@/utils/http/axios';

  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { getValueType } from '/@/utils';
  import { contractDetailInfoSaveOrUpdate, getProductTypeList, getProductContentList } from '../Contracts.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { useMessage } from '/@/hooks/web/useMessage';

  //接收主表id
  const mainId = inject('mainId');
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    itemName: '',
    contractNumber: '',
    unit: '',
    productType: '',
    productContent: '',
    allCount: undefined,
    amount: undefined,
    arriveAmount: undefined,
    thirdExpense: undefined,
    netAmount: undefined,
    taxPrice: undefined,
    trickType: '',
  });

  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  const { createMessage } = useMessage();

  // 产品类型和产品内容相关状态
  const productTypeOptions = ref<any[]>([]);
  const productContentOptions = ref<any[]>([]);
  const productTypeLoading = ref<boolean>(false);
  const productContentLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    productType: [
      { required: false, message: '请输入产品类型', trigger: 'blur' },
    ],
    productContent: [
      { required: false, message: '请输入产品内容', trigger: 'blur' },
    ],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  const props = defineProps({
    disabled: { type: Boolean, default: false },
  });
  const formItemLayout = {
    labelCol: { xs: { span: 24 }, sm: { span: 5 } },
    wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
  };
  
  /**
   * 加载产品类型列表
   */
  async function loadProductTypeList() {
    try {
      productTypeLoading.value = true;
      const response = await getProductTypeList();
      console.log('产品类型API响应:', response);

      // 由于HTTP拦截器会在成功时只返回result字段的数据
      // 所以response实际上就是result数组，不是完整的响应对象
      if (response && Array.isArray(response)) {
        productTypeOptions.value = response;
        console.log('产品类型列表:', productTypeOptions.value);
      } else {
        productTypeOptions.value = [];
        console.log('产品类型API返回数据格式异常:', response);
      }
    } catch (error) {
      console.error('获取产品类型列表失败:', error);
      productTypeOptions.value = [];
    } finally {
      productTypeLoading.value = false;
    }
  }

  /**
   * 加载产品内容列表
   */
  async function loadProductContentList(productTypeId) {
    if (!productTypeId) {
      productContentOptions.value = [];
      return;
    }

    try {
      productContentLoading.value = true;
      const response = await getProductContentList(productTypeId);
      console.log('产品内容API响应:', response);

      // 由于HTTP拦截器会在成功时只返回result字段的数据
      // 所以response实际上就是result数组，不是完整的响应对象
      if (response && Array.isArray(response)) {
        productContentOptions.value = response;
        console.log('产品内容列表:', productContentOptions.value);
      } else {
        productContentOptions.value = [];
        console.log('产品内容API返回数据格式异常:', response);
      }
    } catch (error) {
      console.error('获取产品内容列表失败:', error);
      productContentOptions.value = [];
    } finally {
      productContentLoading.value = false;
    }
  }

  /**
   * 产品类型改变事件
   */
  function handleProductTypeChange(value) {
    // 清空产品内容选择
    formData.productContent = '';

    // 根据产品类型名称找到对应的ID
    const selectedProductType = productTypeOptions.value.find(item =>
      (item.productTypeName || item.productType || item.name) === value
    );

    if (selectedProductType) {
      // 使用产品类型ID加载对应的产品内容列表
      loadProductContentList(selectedProductType.id);
    }
  }

  /**
   * 新增
   */
  function add() {
    edit({
      productType: '',
      productContent: '',
    });
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(async () => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if (record.hasOwnProperty(key)) {
          tmpData[key] = record[key];
        }
      });
      //赋值
      Object.assign(formData, tmpData);

      // 如果有产品类型，根据产品类型名称找到对应的ID，然后加载产品内容列表
      if (formData.productType) {
        const selectedProductType = productTypeOptions.value.find(item =>
          (item.productTypeName || item.productType || item.name) === formData.productType
        );

        if (selectedProductType) {
          await loadProductContentList(selectedProductType.id);
        }
      }
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    try {
      // 触发表单验证
      await validate();
    } catch (e: any) {
      if (e && e.errorFields) {
        const firstField = e.errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(e.errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
   
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    if (unref(mainId)) {
      model['contractNumber'] = unref(mainId);
    }

    console.log('最终提交的数据:', model);

    await contractDetailInfoSaveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res && res.success) {
          createMessage.success('保存成功');
          emit('ok');
        } else {
          const msg = (res && (res.message || res.msg)) || '保存失败';
          createMessage.error(msg);
        }
      })
      .catch((e:any) => {
        const msg = e?.response?.data?.message || e?.message || '请求失败';
        createMessage.error(msg);
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  // 组件挂载时加载产品类型列表
  onMounted(() => {
    loadProductTypeList();
  });

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
